﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Upload2.Models;

namespace Upload2.Controllers
{
	public class HomeController : Controller
	{
		private UpInfoEntity db = new UpInfoEntity();

		public ActionResult Index()
		{
			return View(db.Up.OrderByDescending(u=>u.Id).ToList());
		}
		// GET: WorkInfo/Create
		public ActionResult Create()
		{
			return View();
		}

		// POST: WorkInfo/Create
		// 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
		// 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
		[HttpPost]
		[ValidateAntiForgeryToken]
		public ActionResult Create([Bind(Include = "Id,Title,AttachmentPic,AttachmentFile,AttachmentPaths")] Up up)
		{
			if (ModelState.IsValid)
			{
				db.Up.Add(up);
				db.SaveChanges();
				return RedirectToAction("Index");
			}

			return View(up);
		}

		// GET: WorkInfo/Edit/5
		public ActionResult Edit(int? id)
		{
			if (id == null)
			{
				return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
			}
			Up up = db.Up.Find(id);
			if (up == null)
			{
				return HttpNotFound();
			}
			return View(up);
		}

		// POST: WorkInfo/Edit/5
		// 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
		// 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
		[HttpPost]
		[ValidateAntiForgeryToken]
		public ActionResult Edit([Bind(Include = "Id,Title,AttachmentPaths")] Up up)
		{
			if (ModelState.IsValid)
			{
				db.Entry(up).State = EntityState.Modified;
				db.SaveChanges();
				return RedirectToAction("Index");
			}
			return View(up);
		}




		[HttpPost]
		public JsonResult UpBase64(FormCollection f)
		{
			string base64Image = f["base64Image"];
			string fileName = f["fileName"];

			string upPath = "/UploadFiles/";
			//储存磁盘保存路径文件名
			string filePath = Server.MapPath(upPath);
			if (!Directory.Exists(filePath))
			{
				Directory.CreateDirectory(filePath);
			}
			//相对路径文件名
			string relPathName = Path.Combine(upPath, DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + fileName);
			byte[] bytes = Convert.FromBase64String(base64Image.Split(new string[] { "base64," }, StringSplitOptions.RemoveEmptyEntries)[1]);
			using (FileStream fs = new FileStream(Server.MapPath(relPathName), FileMode.Create))
			{
				fs.Write(bytes, 0, bytes.Length);
			}
			//todo 写数据库
			int iR = 1;
			//返回时去掉路径/UploadFiles
			relPathName = relPathName.Substring(13);
			return Json(new { success = iR > 0, message = iR > 0 ? relPathName : "保存失败" });
		}

	}
}